//
//  DiaryView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/19.
//

import SwiftUI
import Kingfisher
import _PhotosUI_SwiftUI



struct AddDiaryView: View {
    @State var bean : DiaryBean
    @StateObject var viewModel = AddDiaryViewModel()
    @State var text = ""
    @State private var date : Date = Date()
    @State private var mediaItems: [MediaItem] = []
    @State var maxItems = 0
    @State private var showPicker = false //选择图片选择框
    @State private var showFullScreen = false //预览图片
    @State private var selectedIndex = 0
    @State private var isAdd = false
    @State private var showDelDialog = false //删除日记

    
    init(bean: DiaryBean?) {
        let defaultBean = DiaryBean(content: "")
        let integerMilliseconds = Int(Date().timeIntervalSince1970 * 1000)//避免显示小数点
        defaultBean.time = Int64(integerMilliseconds)
        self.bean = bean ?? defaultBean
    }
    
    var body: some View {
        ZStack {
            VStack(alignment: .leading , spacing: 0) {
                VStack(alignment: .leading, spacing: 0) {
                    HStack{
                        VStack(alignment: .leading,spacing: 0){
                            Text("日记时间")
                                .font(.system(size: 14))
                                .foregroundStyle(.bgItemContent)
                            Text("\(TimeUtils.getDate(date: date, format: "yyyy年MM月dd日 HH时mm分"))")
                                .font(.system(size: 14))
                                .foregroundStyle(.bgItemContent)
                                .padding(.top,5)
                        }
                        Spacer()
                        Image(.myIconExpand)
                            .resizable()
                            .frame(width: 15,height: 15)
                            .rotationEffect(Angle(degrees: 270))
                    }.contentShape(Rectangle())
                        .onTapGesture {
                            showTimePopup()
                        }
                    Color.colorLine.frame(height: 0.5).padding(.top,15)
                    ZStack {
                        if text.isEmpty {
                            HStack{
                                Text("写下你完整的日记吧～")
                                    .foregroundColor(.gray)
                                    .font(.system(size: 14))
                                    .padding(.top,8)
                                    .padding(.leading,3)
                                Spacer()
                            }.frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .top)
                        }
                        TextEditor(text: $text)
                            .font(.system(size: 14))
                            .foregroundColor(.bgItemTitle)
                            .textFieldStyle(PlainTextFieldStyle())
                            .scrollContentBackground(.hidden)
                            .background(Color.clear)
                    }.padding(.top,15)
                    
                }.frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .leading)
                    .padding(.top, 20)
                    .padding(.horizontal,15)
                Spacer()
                pictureView
                    .padding(.horizontal, 10)
                    .padding(.bottom,10)
            }.frame(maxWidth: .infinity)
                .background(.bgItem)
                .cornerRadius(15)
                .padding(.horizontal, 20)
                .padding(.vertical,10)
        }.navigationTitle("")
            .frame(maxWidth: .infinity)
            .background(.bg)
            .toolbar {
                // 添加一个右标题按钮
                ToolbarItem(placement: .navigationBarTrailing) {
                    HStack{
                        Text("保存")
                            .foregroundColor(themeManager.themeColor)
                            .font(.system(size: 12))
                            .padding(.horizontal,10)
                            .padding(.vertical,7)
                            .cornerRadius(8)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                viewModel.doSave(bean: bean,mediaItems: mediaItems) {
                                    if isAdd {
                                        NotificationCenter.default.post(name: .addDiary, object: bean) //发送事件
                                    } else {
                                        NotificationCenter.default.post(name: .updateDiary, object: bean) //发送事件
                                    }
                                    pathManager.back()
                                }
                            }
                        if !isAdd {
                            Text("删除")
                                .foregroundColor(.bgDel)
                                .font(.system(size: 12))
                                .padding(.horizontal,10)
                                .padding(.vertical,7)
                                .cornerRadius(8)
                                .contentShape(Rectangle())
                                .onTapGesture {
                                    showDelDialog.toggle()
                                }
                        }
                    }
                }
            }
            .alert("温馨提示",isPresented:$showDelDialog) {
                Button("取消",role: .cancel){}
                Button("确定删除",role: .destructive) {
                    viewModel.delete(bean: bean) {
                        NotificationCenter.default.post(name: .delDiary, object: bean) //发送事件
                        pathManager.back()
                    }
                }
            } message: {
                Text("您确定是否要删除该条数据，删除后将无法恢复")
            }
            .onAppear {
                if !viewModel.isInit{
                    showLog("初始化")
                    //设置ai规则
                    viewModel.setAiRule(bean: $bean, list: bean.aiRule?.listAiRole)
                    requestPhotoLibraryPermission()
                    self.text = bean.content ?? ""
                    let time = bean.time
                    self.date = Date(timeIntervalSince1970: TimeInterval(time) / 1000)
                    self.isAdd = (bean.objectId ?? "").isEmpty
                    viewModel.isInit = true
                    // 添加通知观察者
                    NotificationCenter.default.addObserver(
                        forName: UIApplication.willEnterForegroundNotification,
                        object: nil,
                        queue: .main
                    ) { _ in
                        showLog("应用从后台切换到前台")
                        bean.time = getMillisecond(getNetTimeLocal())
                        self.date = Date(timeIntervalSince1970: getSecond(time: bean.time))
                    }
                }
      
            }.onChange(of: text) { newValue in
                bean.content = newValue
            }
    }
    
    func showTimePopup() {
        hideKeyboard()
        SwiftEntryKitWrapper.showBottomPopup { dissmis in
            PickDateView(title: "    修改时间", selectedDate: $date) {
                bean.time = Int64(date.timeIntervalSince1970 * 1000) //转为毫秒
                dissmis()
            }
        }
    }
}

extension AddDiaryView {
    //图片列表
    var pictureView: some View {
        ScrollView(.horizontal,showsIndicators: false) {
            //横向布局
            HStack(spacing:7) {
                ForEach(Array(mediaItems.enumerated()), id: \.element.id) { index, item in
                    ZStack(alignment:.topTrailing) {
                        PictureItemView(item: item,itemWidth: 50, itemHeight: 50, cornerRadius: 15)
                        Image(.appIconImageDel)
                            .resizable()
                            .frame(width: 15,height: 15)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                // 使用 if case 语句判断是否为 networkImage
                                if case let .networkImage(_, url2, _) = item.type {
                                    if let picture = bean.listDiaryPicture?.first(where: {$0.url ?? "" == url2}){
                                        viewModel.delPicture.append(picture)
                                    }
                                }
                                mediaItems.remove(at: index)
                            }
                        
                    }.onTapGesture {
                        selectedIndex = index
                        showFullScreen.toggle()
                    }
                }
                if mediaItems.count < 9 {
                    //添加按钮
                    Image(.appPhoto)
                        .resizable()
                        .scaledToFill()
                        .padding(10)
                        .frame(width: 50,height: 50)
                        .background(.bg)
                        .clipShape(RoundedRectangle(cornerRadius: 15))
                        .contentShape(Rectangle())
                        .onTapGesture {
                            if BackupsManager.shared.getDelegateConfig()?.checkCloudCapacity() == true {
                                let capacity = BackupsManager.shared.getDelegateConfig()?.getUploadCapacity() ?? 0
                                self.maxItems = capacity - mediaItems.count
                                showLog("maxItems:\(maxItems)")
                                if self.maxItems <= 0 {
                                    showLog("数量不够")
                                    showToast("数量不够")
                                } else {
                                    showPicker.toggle()
                                }
                            }
                        }
                    
                }
            }
        }
        .sheet(isPresented: $showPicker) {
            MediaPicker(
                selectionLimit: $maxItems,
                maxFileSizeMB: 100, // 100MB
                filterType: MediaFilterType.all,
                isPresented: $showPicker,
                onComplete: { items in
                    showPicker = false 
                    mediaItems.append(contentsOf: items)
                }
            )
        }
        .fullScreenCover(isPresented: $showFullScreen) {
            FullScreenMediaView(mediaItems: mediaItems, currentIndex: $selectedIndex)
        }
        .onAppear{
            if mediaItems.isEmpty {
                bean.listDiaryPicture?.forEach {
                    if let mediaItem = DiaryExt.getMediaItem($0) {
                        mediaItems.append(mediaItem)
                    }
                }
            }
        }
    }
}

#Preview {
    AddDiaryView(bean: nil)
}

